const querystring = require('querystring');;
const handleBlogRouter = require('./src/router/blog');
const handleUserRouter = require('./src/router/user');

const setResIsJson = (res) => {
  res.setHeader('Content-type', 'application/json')
}
const setReqPath = (req) => {
  const url = req.url;
  req.path = url.split('?')[0]
}
const setReqQurey = (req) => {
  const url = req.url;
  req.query = querystring.parse(url.split('?')[1])
}
const setReqCookie = (req) => {
  // 解析 cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || ''  // k1=v1;k2=v2;k3=v3
  cookieStr.split(';').forEach(item => {
    if (!item) {
      return
    }
    const arr = item.split('=')
    const key = arr[0].trim()
    const val = arr[1].trim()
    req.cookie[key] = val
  })
}
// session 数据
const SESSION_DATA = {};
const setReqSession = (req) => {
  // 解析 session
  let needSetCookie = false
  let userId = req.cookie.userid
  if (userId) {
    if (!SESSION_DATA[userId]) {
      SESSION_DATA[userId] = {}
    }
  } else {
    needSetCookie = true
    userId = `${Date.now()}_${Math.random()}`
    SESSION_DATA[userId] = {}
  }
  req.needSetCookie = needSetCookie;
  req.session = SESSION_DATA[userId]
}

// 用于处理 post data
const setReqPostData = (req) => {
  const promise = new Promise((resolve, reject) => {
    if (req.method !== 'POST') {
      resolve({})
      return
    }
    if (req.headers['content-type'] !== 'application/json') {
      resolve({})
      return
    }
    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      if (!postData) {
        resolve({})
        return
      }
      resolve(
        JSON.parse(postData)
      )
    })
  }).then((postData) => {
    req.body = postData;
  });
  return promise
}

resNoRouter = (res) => {
  res.writeHead(404, { "Content-type": "text/plain" })
  res.write("404 Not Found\n")
  res.end()
}

const serverHandle = (req, res) => {
  // 增强req对象
  setReqPath(req); // 获取 path
  setReqQurey(req); // 解析 query
  setReqCookie(req); // 解析 cookie
  setReqSession(req); // 设置 session

  // 设置res对象
  setResIsJson(res); // 设置返回格式 JSON

  // 封装post请求
  setReqPostData(res).then(() => {
    const blogResult = handleBlogRouter(req, res);
    if (blogResult) return;

    const userResult = handleUserRouter(req, res);
    if (userResult) return;

    // 未命中路由，返回 404
    resNoRouter(res);
  });
}

module.exports = serverHandle;